// backend/src/modules/system-monitor/systemMonitor.js
const os = require("os");
const { exec } = require("child_process");
const util = require("util");
const execPromise = util.promisify(exec);

async function getMemoryInfo() {
  try {
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    return {
      total: totalMem,
      free: freeMem,
      used: totalMem - freeMem,
    };
  } catch (e) {
    console.error("Error getting memory info:", e);
    return { error: "Failed to retrieve memory information" };
  }
}

async function getGpuInfo() {
  try {
    const { stdout } = await execPromise(
      "nvidia-smi --query-gpu=name,memory.total,memory.used,memory.free --format=csv,noheader,nounits"
    );
    const gpus = stdout
      .trim()
      .split("\n")
      .map((line) => {
        const [name, total, used, free] = line
          .split(",")
          .map((item) => item.trim());
        return {
          model: name,
          total: parseInt(total),
          used: parseInt(used),
          free: parseInt(free),
        };
      });
    return gpus;
  } catch (e) {
    console.error("Error getting GPU info:", e);
    return { error: "Failed to retrieve GPU information" };
  }
}

async function getSystemInfo() {
  const [memory, gpus, platformInfo] = await Promise.all([
    getMemoryInfo(),
    getGpuInfo(),
    getPlatformInfo(),
  ]);

  return {
    platform: platformInfo,
    memory,
    gpus,
  };
}

async function getPlatformInfo() {
  try {
    const cpus = os.cpus();
    return {
      model: cpus[0].model,
      cores: cpus.length,
      arch: os.arch(),
      platform: os.version(),
      release: os.release(),
    };
  } catch (e) {
    console.error("Error getting CPU info:", e);
    return { error: "Failed to retrieve CPU information" };
  }
}

module.exports = {
  getSystemInfo,
  getMemoryInfo,
  getGpuInfo,
};
